﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using QRCodeNet;
using Emgu.CV;
using System.Drawing;
using Emgu.CV.Structure;
using ZXing;
using System.Diagnostics;
using ZXing.Multi.QrCode;
using ZXing.Common;

namespace UnitTest
{
	[TestClass]
	public class UnitTest1
	{
		[TestMethod]
		public void TestMethod1()
		{
			var cfg = Config.config;
			Mat m = CvInvoke.Imread(@"C:\Users\Administrator\Desktop\Snapshot-2017013015241723668175.JPG");

			//Multi QRCode
			QRCodeMultiReader mreader = new QRCodeMultiReader();
			LuminanceSource source = new BitmapLuminanceSource(m.Bitmap);
			BinaryBitmap bbmp = new BinaryBitmap(new HybridBinarizer(source));
			Result[] results = mreader.decodeMultiple(bbmp);
			foreach (var item in results)
			{
				Debug.WriteLine($"Multi: {item.Text}");
			}

			int x = cfg.XOffset, y = cfg.YOffset;
			int wid = cfg.QRWid, hei = cfg.QRHei;
			for (int i = 0; i < cfg.EachCol; i++)
			{
				for (int j = 0; j < cfg.EachRow; j++)
				{
					Rectangle roi = new Rectangle(x, y, wid, hei);
					if (roi.Right > m.Cols) roi.Width -= (roi.Right - m.Cols);
					if (roi.Bottom > m.Rows) roi.Height -= (roi.Bottom - m.Rows);

					//Single QRCode
					Mat qr = new Mat(m, roi);
					IBarcodeReader reader = new BarcodeReader();
					var barcodeBitmap = (Bitmap)qr.Bitmap.Clone();
					var result = reader.Decode(barcodeBitmap);

					if (result != null)
					{
						CvInvoke.Rectangle(m, roi, new MCvScalar(255, 255, 255), 2);
						Debug.WriteLine(result);
					}
					x += cfg.QRWid;
				}
				x = cfg.XOffset;
				y += cfg.QRHei;
			}
			CvInvoke.NamedWindow("1");
			CvInvoke.Imshow("1", m);
			CvInvoke.WaitKey(0);
		}
	}
}
